package com.jiaai.shop.store.api;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jiaai.shop.OnPayThread;
import com.jiaai.shop.store.entity.SGoods;
import com.jiaai.shop.store.entity.SMember;
import com.jiaai.shop.store.entity.SOrder;
import com.jiaai.shop.store.entity.TIntegralHistory;
import com.jiaai.shop.store.service.*;
import com.jiaai.shop.util.CacheManage;
import com.jiaai.shop.util.MD5;
import com.jiaai.shop.util.ThreadPoolProxy;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Member;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;

import static com.jiaai.shop.util.CacheManage.getSystemConfig;

/**
 * Created by Administrator on 2018\5\4 0004.
 */

@RequestMapping("/app/pay")
@Controller
public class PayController {
    private static final String NOTIF_URL="http://jiai.tpddns.cn:8788/app/pay/notifyurl";
    private static final String CALLBACK_URL="http://jiai.tpddns.cn:8788/app/pay/callback";
    private static final Logger log= LoggerFactory.getLogger(PayController.class);
    private static final SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final String  PAY_MEMBERID="10187";
    private static  final  String PAY_KEY="6392yb75l84wvblgtbopbu5pmd1uk4ku";

    @Autowired
    private ThreadPoolProxy poolProxy;
    @Autowired
    private ISGoodsService goodsService;
    @Autowired
    private ISOrderService orderService;

    @Autowired
    private ISMemberService memberService;

    @Autowired
    private ITIntegralHistoryService integralHistoryService;

    /**
     * 创建支付订单
     * @param goodsId
     * @return
     */
    @GetMapping("/ceatePayOrder/{mId}")
    public String createPayOrder(@PathVariable("mId") String mId, Integer goodsId, Model model, HttpServletRequest request){
        SGoods goods=goodsService.selectById(goodsId);
        SOrder order=new SOrder();
        order.setGoodsId(goods.getId());
        order.setGoodsImg(order.getGoodsImg());
        order.setGoodsName(goods.getGoodsName());
        order.setGoodsPrice(goods.getGoodsPrice());
        order.setOrderId(generateOrderId());
        order.setMemberId(mId);
        orderService.insert(order);
        String payOrderDate=dateFormat.format(order.getCreateTime());
        String pay_bankcode="904";
        model.addAttribute("pay_memberid",PAY_MEMBERID);
        model.addAttribute("pay_orderid",order.getOrderId());
        model.addAttribute("pay_applydate",payOrderDate);
        model.addAttribute("pay_bankcode",pay_bankcode);
        model.addAttribute("pay_notifyurl",NOTIF_URL);
        model.addAttribute("pay_callbackurl",CALLBACK_URL);
        model.addAttribute("pay_amount",order.getGoodsPrice());
        model.addAttribute("pay_productname",order.getGoodsName());
        model.addAttribute("pay_productnum",1);
        String stringSignTemp="pay_amount="+order.getGoodsPrice()+"&pay_applydate="+payOrderDate+"&pay_bankcode="+pay_bankcode+"&pay_callbackurl="+CALLBACK_URL+"&pay_memberid="+PAY_MEMBERID+"&pay_notifyurl="+NOTIF_URL+"&pay_orderid="+order.getOrderId()+"&key="+PAY_KEY+"";
        String pay_md5sign= MD5.MD5Encode(stringSignTemp).toUpperCase();
        model.addAttribute("pay_md5sign",pay_md5sign);
        return "payOrder";
    }
    @RequestMapping("/notifyur")
    public void onPayNotifyur(HttpServletRequest request, HttpServletResponse response){
        try {

            String returncode=request.getParameter("returncode");
            if(returncode.equals("00")){
                //支付成功，写返回数据逻辑
                PrintWriter pw=response.getWriter();
                pw.write("ok");
            }else{
                PrintWriter pw=response.getWriter();
                pw.write("支付失败");
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }

    }
    @RequestMapping("/callback")
    public String onPayCallback(Model model,HttpServletRequest request, HttpServletResponse response){
        String orderid=request.getParameter("orderid");
        String returncode=request.getParameter("returncode");

        if(returncode.equals("00")){
            SOrder  order=orderService.selectOne(new EntityWrapper().eq("orderId",orderid));
            SGoods goods=goodsService.selectById(order.getGoodsId());
            model.addAttribute("integral",goods.getIntegral());
            poolProxy.commitTask(new OnPayThread(orderid));
          return "onPayCallback";
        }else{
            return "onPayError";
        }

    }

    private String generateOrderId(){
        String keyup_prefix=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String keyup_append=String.valueOf(new Random().nextInt(899999)+100000);
        String pay_orderid=keyup_prefix+keyup_append;//订单号
        return pay_orderid;
    }


}
